package com.atguigu.app.dws;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.SttEdtTs2;
import com.atguigu.bean.UserLoginBean4;
import com.atguigu.func.SttEdtTsFunction;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.KafkaUtil;
import com.atguigu.utils.MyClickhouseUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/*
10.4 用户域用户登录各窗口汇总表
10.4.1 主要任务
从 Kafka 页面日志主题读取数据，统计七日回流（回归）用户和当日独立用户数。
10.4.2 思路分析
之前的活跃用户，一段时间未活跃（流失），今日又活跃了，就称为回流用户。此处要求统计回流用户总数。规定当日登录，且自上次登录之后至少 7 日未登录的用户为回流用户。

 */
//todo 1.创建环境,读取kafka dwd页面日志数据
//todo 3.过滤出登录的数据，并将数据转化为json格式
//todo 4.按照uid进行分组
//todo 5.利用状态编程标记独立用户和七日回流用户并转为javabean
//todo 6.提取事件时间和watermark
//todo 7.开窗、聚合
//todo 8.将数据写到clickhouse
//todo 9.启动任务
public class Dws04UserUserLoginWindow {
    public static void main(String[] args) throws Exception {
        //todo 1.创建环境,读取kafka dwd页面日志数据
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> kafkaDS = env.addSource(KafkaUtil.getFlinkKafkaConsumer("page_topic", "userlogin_220828"));

        //todo 2.设置状态后端

        //todo 3.过滤出登录的数据，并将数据转化为json格式
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                String uid = jsonObject.getJSONObject("common").getString("uid");
                String lastPageId = jsonObject.getJSONObject("page").getString("last_page_id");
                if (uid != null && (("login").equals(lastPageId) || lastPageId == null)) {
                    out.collect(jsonObject);
                }
            }
        });

        //todo 4.按照uid进行分组
        KeyedStream<JSONObject, String> keyByUidDS = jsonObjDS.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getJSONObject("common").getString("uid");
            }
        });
//        keyByUidDS.print("keyByUidDS>>>");
        //todo 5.利用状态编程标记独立用户和七日回流用户并转为javabean
        SingleOutputStreamOperator<UserLoginBean4> userLoginBeanDS = keyByUidDS.flatMap(new RichFlatMapFunction<JSONObject, UserLoginBean4>() {
            //定义状态
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //初始化状态
                valueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("uid-state", String.class));

            }

            @Override
            public void flatMap(JSONObject value, Collector<UserLoginBean4> out) throws Exception {
                //获取状态
                String lastDt = valueState.value();

                //获取今天日期
                String curDt = DateFormatUtil.toDate(value.getLong("ts"));

                //定义两个变量，分别标记是否为独立用户和七日回流用户
                Long uuCt=0L;
                Long backCt=0L;
                if (lastDt==null ){
                //说明是用户今天（历史至今）第一条登录，一定是独立用户，一定不是回流用户
                   uuCt=1L;
                   valueState.update(curDt);
                }else if (lastDt.compareTo(curDt)<0){
                    //说明用户今天第一条登录，是独立用户，有可能是回流用户
                    uuCt=1L;
                    valueState.update(curDt);
                    if (DateFormatUtil.toTs(curDt,false)-DateFormatUtil.toTs(lastDt,false)>7*24*3600*1000){
                        //日期至少相差7天，说明是七日回流用户
                        backCt=1L;
                    }
                }

                if (uuCt==1L) {
                    out.collect(new UserLoginBean4());

                    out.collect(UserLoginBean4.builder()
                            .backCt(backCt)
                            .uuCt(uuCt)
                            .ts(value.getLong("ts"))
                            .build());

                }
            }

        });

//        userLoginBeanDS.print("userLoginBeanDS>>>");
        //todo 6.提取事件时间和watermark
        SingleOutputStreamOperator<UserLoginBean4> userLoginBeanWithWMDS = userLoginBeanDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<UserLoginBean4>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(new SerializableTimestampAssigner<UserLoginBean4>() {
                            @Override
                            public long extractTimestamp(UserLoginBean4 element, long recordTimestamp) {
                                return element.getTs();
                            }
                        })

        );

//        userLoginBeanWithWMDS.print("userLoginBeanWithWMDS>>>");

        //todo 7.开窗、聚合
        SingleOutputStreamOperator<Object> resultDS = userLoginBeanWithWMDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<UserLoginBean4>() {
                    @Override
                    public UserLoginBean4 reduce(UserLoginBean4 value1, UserLoginBean4 value2) throws Exception {

                        value1.setBackCt(value1.getBackCt()+value2.getBackCt());
                        value1.setUuCt(value1.getUuCt()+value2.getUuCt());
                        return value1;
                    }
                }, new AllWindowFunction<UserLoginBean4, Object, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<UserLoginBean4> values, Collector<Object> out) throws Exception {
                        UserLoginBean4 next = values.iterator().next();

//                        next.setTs(System.currentTimeMillis());
//                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
//                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
//                        out.collect(next);


//                        SttEdtTsFunction.getSttEdtTs(next,window,out);
//                        SttEdtTs2.getSttEdtTs(next,window,out);
                        next.getSttEdtTs(next,window,out);
                    }
                });

        resultDS.print("即将写入clickhouse的数据：");
        //todo 8.将数据写到clickhouse
        resultDS.addSink(MyClickhouseUtil.getSinkFunction("insert into dws_user_user_login_window values(?,?,?,?,?)"));

        //todo 9.启动任务
        env.execute("Dws04UserUserLoginWindow");

    }
}
